<?php

require 'D:/phpstudy_pro/WWW/vendor/autoload.php';

use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;

$server = '47.96.100.201';
$port = 1883;
$clientId = 'R667A76CDB';
$username = 'emqx_user';
$password = null;
$clean_session = false;

$connectionSettings = new ConnectionSettings();
$connectionSettings
    ->setUsername($username)
    ->setPassword(null)
    ->setKeepAliveInterval(60)
    // Last Will 设置
    ->setLastWillTopic('emqx/test/last-will')
    ->setLastWillMessage('client disconnect')
    ->setLastWillQualityOfService(1);


$mqtt = new MqttClient($server, $port, $clientId);

$mqtt->connect($connectionSettings, $clean_session);
printf("客户端连接\n");
//客户端收到消息
$mqtt->subscribe('CIOT/2000/DEVICE/R667A76CDB', function ($topic, $message) {
    printf("收到主题消息 [%s]: %s\n", $topic, $message);
}, 0);

for ($i = 0; $i < 10; $i++) {

    // {"Header":{"Code":"1004","Time":1682220193000,"Sign":"lvzaina"},"Body":{"MsgId":1,"Cmd":"RemoteOpenDoor","ID":1,"Delay":3000,"Type":0,"Lock":0}}
    $payload = ['Header' => ['Code' => 1004, 'Time' => 1682220193000, 'Sign' => 'lvzaina'],
        'Body' => ['MsgId' => 1, 'Cmd' => 'RemoteOpenDoor','ID'=>1,'Delay'=>3000,'Type'=>0,'Lock'=>0]];
//向客户端发送消息
    $mqtt->publish(
    // topic
        'CIOT/2000/DEVICE/R667A76CDB',
        // payload
        json_encode($payload),
        // qos
        0,
        // retain
        true
    );
    printf("msg $i send\n");
    sleep(1);
}

$mqtt->loop(true);
